﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace SimpleServerWarp
{
    public partial class WrapService : ServiceBase
    {
        private static readonly string wrap_exe_name_key = "wrap_exe_name";
        private static readonly string wrap_exe_paras_key = "wrap_exe_paras";
        private static readonly string wrap_exe_name = ConfigurationManager.AppSettings[wrap_exe_name_key];
        private static readonly string wrap_exe_paras = ConfigurationManager.AppSettings[wrap_exe_paras_key];
        private Process pmain = null; 
        public WrapService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            try
            {
                pmain = new Process();
                pmain.StartInfo.FileName = wrap_exe_name;
                pmain.StartInfo.Arguments = wrap_exe_paras;
                pmain.StartInfo.WorkingDirectory = path;
                pmain.Start();
            }
            catch (Exception ex)
            {
                LogHandler.Handle(ex,string.Format("wrap_exe_name:{0},wrap_exe_paras:{1},path:{2}", wrap_exe_name, wrap_exe_paras, path));
            }
        }

        protected override void OnStop()
        {
            try
            {
                if (pmain != null && !pmain.HasExited)
                {
                    pmain.Kill();
                    pmain.WaitForExit();
                    pmain.Dispose();
                    pmain = null;
                }
            }
            catch (Exception ex)
            {
                LogHandler.Handle(ex);
            }
        }
    }
}
